<script setup lang="ts">
import "@wangeditor/editor/dist/css/style.css";
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
import { onBeforeUnmount, ref, shallowRef, onMounted, watch } from "vue";
import { formUpload } from "@/api/mock";

defineOptions({
  name: "BaseEditor"
});

const props = defineProps({
  modelValue: {
    type: String,
    default: ""
  }
});

const emits = defineEmits(["update:modelValue"]);

const mode = "default";
// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef();

// 内容 HTML
const valueHtml = ref(props.modelValue);

// 监听 props.modelValue 的变化，更新 valueHtml
watch(
  () => props.modelValue,
  (newVal, oldVal) => {
    if (newVal !== valueHtml.value) {
      valueHtml.value = newVal;

      // 如果编辑器已经创建，同步更新编辑器内容
      if (editorRef.value) {
        try {
          // 检查是否是重置操作（内容为空或默认值）
          const isReset = !newVal || newVal === "" || newVal === "<p><br></p>";

          if (isReset) {
            // 重置操作：清空编辑器内容
            editorRef.value.clear();
          } else if (editorRef.value.getHtml() !== newVal) {
            // 正常更新：设置新内容
            editorRef.value.setHtml(newVal);
          }
        } catch (error) {
          console.warn("WangEditor 内容更新失败:", error);
          // 如果更新失败，尝试重新创建编辑器内容
          setTimeout(() => {
            if (editorRef.value && editorRef.value.getHtml() !== newVal) {
              try {
                editorRef.value.setHtml(newVal || "");
              } catch (retryError) {
                console.error("WangEditor 重试更新失败:", retryError);
              }
            }
          }, 100);
        }
      }
    }
  },
  { immediate: true }
);

// 监听 valueHtml 的变化，发出 update:modelValue 事件
watch(valueHtml, newVal => {
  console.log("WangEditorBase emits update:modelValue:", newVal); // 添加调试日志
  emits("update:modelValue", newVal);
});

const toolbarConfig: any = { excludeKeys: "fullScreen" };
const editorConfig: any = {
  placeholder: "请输入内容...",
  scroll: true,
  autoFocus: false,
  readOnly: false,
  maxLength: 50000,
  MENU_CONF: {
    uploadImage: {
      customUpload(file: File, insertFn: (url: string, alt: string, href: string) => void) {
        const formData = new FormData();
        formData.append("file", file);
        formUpload(formData)
          .then(res => {
            console.log("图片上传结果:", res);
            if (res.code === 200) {
              const imageUrl = import.meta.env.VITE_BASE_URL + res.data.url;
              console.log("图片URL:", imageUrl);
              const filename = res.data.url ? res.data.url.substring(res.data.url.lastIndexOf("/") + 1) : "";
              insertFn(imageUrl, filename, imageUrl); // 插入图片
            } else {
              console.error("图片上传失败");
            }
          })
          .catch(error => {
            console.error("图片上传请求失败:", error);
          });
      }
    }
  }
};

const handleCreated = editor => {
  console.log("WangEditor 创建成功:", editor);

  // 记录 editor 实例，重要！
  editorRef.value = editor;

  // 延迟初始化内容，确保编辑器完全准备好
  setTimeout(() => {
    try {
      if (props.modelValue && editor.getHtml() !== props.modelValue) {
        editor.setHtml(props.modelValue);
      }
    } catch (error) {
      console.warn("WangEditor 初始化内容设置失败:", error);
    }
  }, 100);
};

// 添加清空编辑器的方法
const clearEditor = () => {
  if (editorRef.value) {
    try {
      editorRef.value.clear();
      valueHtml.value = "";
      emits("update:modelValue", "");
    } catch (error) {
      console.warn("WangEditor 清空失败:", error);
    }
  }
};

// 暴露清空方法给父组件
defineExpose({ clearEditor });

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value;
  if (editor == null) return;

  try {
    // 确保编辑器正确销毁
    if (!editor.isDestroyed) {
      editor.destroy();
    }
  } catch (error) {
    console.warn("WangEditor 销毁时出现错误:", error);
  }
});
</script>

<template>
  <div class="wangeditor">
    <Toolbar
      :editor="editorRef"
      :defaultConfig="toolbarConfig"
      :mode="mode"
      style="border-bottom: 1px solid #ccc"
    />
    <Editor
      v-model="valueHtml"
      :defaultConfig="editorConfig"
      :mode="mode"
      style="height: 450px; min-height: 450px; overflow-y: hidden"
      @onCreated="handleCreated"
      @onChange="editor => (valueHtml = editor.getHtml())"
    />
  </div>
</template>
<style scoped>
.wangeditor {
  min-height: 500px;
  border: 1px solid #ccc;
}

/* 确保编辑区域有足够高度 */
.wangeditor :deep(.w-e-text-container) {
  min-height: 350px !important;
}

.wangeditor :deep(.w-e-scroll) {
  min-height: 350px !important;
}

/* 工具栏样式优化 */
.wangeditor :deep(.w-e-toolbar) {
  background-color: #fafafa;
  border-bottom: 1px solid #ccc;
}
</style>
